package com.hontech.pastacooking.app

import android.os.Handler
import com.hontech.pastacooking.except.WaitRespTimeoutException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout

typealias Promise<T> = CompletableDeferred<T>

fun<T> promise() = CompletableDeferred<T>()

suspend fun<T> Promise<T>.await(timeout: Long): T {
    try {
        return withTimeout(timeout) {
            await()
        }
    } catch (e: TimeoutCancellationException) {
        e.printStackTrace()
        throw WaitRespTimeoutException("等待返回超时:${timeout}ms")
    }
}

class Task (private val cb: () -> Unit) : Runnable {

    fun exec(task: Handler) {
        task.post(this)
    }

    override fun run() {
        try {
            cb()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

class PromiseTask<T>(private val cb: () -> T) : Runnable {

    private val promise = promise<T>()

    fun exec(task: Handler): PromiseTask<T> {
        task.post(this)
        return this
    }

    suspend fun await() = promise.await()

    suspend fun await(timeout: Long) = promise.await(timeout)

    override fun run() {

        try {
            val ret = cb()
            promise.complete(ret)
        } catch (e: Exception) {
            promise.completeExceptionally(e)
        }
    }
}


